import base64
import datetime
import logging
from flask import Blueprint, render_template, request, jsonify
from bilibili_api import search, sync, video
from exts import db
from models import MonitoringTask, MonitoredVideo, Comment, Alert
import requests
import asyncio
from script.spider_common_method import save_video, filter_string, get_all_comment, update_comment, \
    delete_video_comments, \
    re_crawling_video_comments
from utils.CredentialUtil import CredentialConfig

alert_bp = Blueprint("alert", __name__, url_prefix="/alert")


@alert_bp.route("/")
def views():
    return render_template("alert.html")


@alert_bp.route("/change", methods=['POST'])
def change():
    # 从 POST 请求中获取 JSON 数据
    data = request.get_json()
    # 提取 videoId 和 alertStandard
    video_bvid = data.get('video_bvid')
    alert_standard = data.get('alert_standard')
    alert_rate = data.get('alert_rate')

    if alert_rate:
        alert = Alert.query.filter_by(video_bvid=video_bvid).first()
        if alert:
            db.session.delete(alert)
        video = MonitoredVideo.query.filter_by(bvid=video_bvid).first()
        video.alert_rate = float(alert_rate)
        if (video.violence_count / video.comment_count) >= video.alert_rate:
            task_id = db.session.query(MonitoringTask).filter(
                MonitoringTask.monitored_videos.like(f'%{video_bvid}%')).first().id
            alert = Alert(alert_time=datetime.datetime.now(), video_bvid=video_bvid, alert_rate=alert_rate,
                          task_id=task_id,
                          is_active=True)
            db.session.add(alert)
        db.session.commit()
        return jsonify({'success': 'Data received successfully'}), 200
    elif alert_standard:
        alert = Alert.query.filter_by(video_bvid=video_bvid).first()
        if alert:
            db.session.delete(alert)
        video = MonitoredVideo.query.filter_by(bvid=video_bvid).first()
        video.alert_standard = int(alert_standard)
        if (video.violence_count / video.comment_count) >= video.alert_rate:
            task_id = db.session.query(MonitoringTask).filter(
                MonitoringTask.monitored_videos.like(f'%{video_bvid}%')).first().id
            alert = Alert(alert_time=datetime.datetime.now(), video_bvid=video_bvid, alert_by=alert_standard,
                          task_id=task_id,
                          is_active=True)
            db.session.add(alert)
        db.session.commit()
        return jsonify({'success': 'Data received successfully'}), 200

    else:
        return jsonify({'error': 'error not have value'}), 500


@alert_bp.route("/all")
def alert_by_all():
    try:
        all_alerts = Alert.query.all()
        videos = []
        for a in all_alerts:
            v = MonitoredVideo.query.filter_by(bvid=a.video_bvid).first().__dict__
            del v['_sa_instance_state']
            videos.append(v)
        return jsonify({'data': {'videos': videos}}), 200
    except Exception as e:
        return jsonify({'error': 'Failed to fetch zone monitoring tasks'}), 500


@alert_bp.route("/violence")
def alert_by_violence():
    try:
        all_alerts = Alert.query.filter_by(alert_by=0).all()
        videos = []
        for a in all_alerts:
            v = MonitoredVideo.query.filter_by(bvid=a.video_bvid).first().__dict__
            del v['_sa_instance_state']
            videos.append(v)
        return jsonify({'data': {'videos': videos}}), 200
    except Exception as e:
        return jsonify({'error': 'Failed to fetch zone monitoring tasks'}), 500


@alert_bp.route("/sarcasm")
def alert_by_sarcasm():
    try:
        all_alerts = Alert.query.filter_by(alert_by=1).all()
        videos = []
        for a in all_alerts:
            v = MonitoredVideo.query.filter_by(bvid=a.video_bvid).first().__dict__
            del v['_sa_instance_state']
            videos.append(v)
        return jsonify({'data': {'videos': videos}}), 200
    except Exception as e:
        return jsonify({'error': 'Failed to fetch zone monitoring tasks'}), 500


@alert_bp.route("/did")
def alert_by_did():
    try:
        all_alerts = Alert.query.filter_by(alert_by=2).all()
        videos = []
        for a in all_alerts:
            v = MonitoredVideo.query.filter_by(bvid=a.video_bvid).first().__dict__
            del v['_sa_instance_state']
            videos.append(v)
        return jsonify({'data': {'videos': videos}}), 200
    except Exception as e:
        return jsonify({'error': 'Failed to fetch zone monitoring tasks'}), 500
